import Vue from "vue";
import VueRouter from "vue-router";
import Charity from "./charity-R";
import Dream from "./dream-R";
import Home from "./home-R";
import Profile from "./profile-R";
import { Login } from "./login-register-R";
import Search from "./serach-R";
import Pay from "./pay-R";
import Goods from "./goods-R";
import myStore from "store/index";
import cfpay from "./cfpay-R";
import dreampay from "./dreampay-R";

import Detail from "./detail-R";

// 引入loading组件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 简单的配置，一般情况speed配置为500
NProgress.inc(0.4)
NProgress.configure({ easing: 'ease', speed:800, showSpinner: false })


// 解决重复点击路由报错的BUG
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(warn => {
    console.warn(warn);
  });
};

Vue.use(VueRouter);
// 此处做好了抽离

const routes = [
  {
    path: "",
    redirect: "/home"
  },
  Home,
  Charity,
  Dream,
  Login,
  Profile,
  Detail,
  Search,
  Pay,
  Goods,
  cfpay,
  dreampay
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  // 页面切换时回到页面顶部
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
});
/*
  全局导航守卫
*/
router.beforeEach((to, from, next) => {
  console.log("from:");
  console.log(from);
  console.log("to:");
  console.log(to);
  // 开启loading组件
  // NProgress.start();
  console.log(sessionStorage.getItem("userToken"));
  if (sessionStorage.getItem("userToken")) {
    myStore.state.isLogin = true;
  }
  if (
    to.name === "persen" &&
    (sessionStorage.getItem("userToken") === undefined ||
      sessionStorage.getItem("userToken") === "" ||
      sessionStorage.getItem("userToken") === null)
  ) {
    next({ name: "login" });
  }
  // else next();
  else {
    next();
  }
});
// 路由响应后关闭loading组件
router.afterEach(()=>{
  NProgress.done()
})
/** 捕获到错误重新加载路由 */
router.onError(error => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});

export default router;
